package org.example.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileChannel;

/**
 * @author liu-rui
 * @date 2020/5/27 下午2:16
 * @description interrupt 可以打断java.nio.channels.InterruptibleChannel上的IO操作的线程
 * @since
 */
@Slf4j
public class Demo9 {
    public static void main(String[] args) throws InterruptedException {
        final Thread thread = new Thread(() -> {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);

            log.info("begin");
            try (FileInputStream inputStream = new FileInputStream("/home/liurui/mine/test/2.log")) {
                try (FileChannel fileChannel = inputStream.getChannel()) {
                    try (FileOutputStream outputStream = new FileOutputStream("/home/liurui/mine/test/3.log")) {
                        try (final FileChannel outputStreamChannel = outputStream.getChannel()) {
                            byteBuffer.rewind();
                            final int read = fileChannel.read(byteBuffer); //此处会抛出ClosedByInterruptException异常

                            if (read == -1) {
                                log.info("读取到最后了");
                                return;
                            }
                            byteBuffer.flip();
                            outputStreamChannel.write(byteBuffer);
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (ClosedByInterruptException e) {
                log.error(String.format("由于中断而退出　%s", Thread.currentThread().isInterrupted()), e);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "t1");

        thread.start();
        thread.interrupt();
    }
}
